<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Exceptions\InvalidRequestException;
use App\Models\ApprovalNode;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class ApprovalNodeService
{
    public function get($title)
    {
        $sql = ApprovalNode::when($title, function ($query, $title) {
            return $query->where(function($query) use ($title) {
                $query->where('name','like', '%'.$title.'%');
            });
        });
        return $sql;
    }

    public function insert($input){
        try {
            ApprovalNode::where('flow_id',$input['flow_id'])->delete();
            $nodes = json_decode($input['nodes']);
            $insert = [];
            foreach ($nodes as $k => $v) {
                $arr = [];
                $arr['admin_id'] = $v->admin_id ? $v->admin_id : 0;
                $arr['flow_id'] = $input['flow_id'];
                $arr['name'] = $v->name;
                $arr['role_id'] = $v->role_id;
                $insert[] = $arr;
            }
            $data = ApprovalNode::insert($insert);
            if($data){
                return $data;
            }
        } catch (\Exception $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input){
        $res = [];
        foreach ($input as $k => $v) {
            if($v){
                $res[$k] = $v;
            }
        }
        $res['status'] = $input['status'] == true ? 1 : 0;
        unset($res['id']);
        try {
            $data = ApprovalNode::where('id',$input['id'])->update($res);
            if($data){
                return $input['id'];
            }
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}